package com.github.chirspan.xaas.minio.config;

import io.minio.MinioClient;
import io.minio.errors.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * *******description*******
 * minio配置
 * *************************
 *
 * @author chenpan
 * @date 2020/6/3 16:02
 */
@Data
@Configuration
@ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true")
@Slf4j
public class MinioConfiguration {

    @Autowired
    private MinioConfigurationProperties configurationProperties;

    @Bean
    public MinioClient minioClient() {
        MinioClient client = null;
        try {
            client = new MinioClient(configurationProperties.getBaseUrl(),
                    configurationProperties.getAccessKey(), configurationProperties.getSecretKey());
            if (!client.bucketExists(configurationProperties.getBucket())) {
                client.makeBucket(configurationProperties.getBucket());
            }
        } catch (InvalidPortException | InvalidEndpointException e) {
            log.error("创建MinioClient失败：{}", e.getMessage());
        } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidResponseException | InvalidBucketNameException
                | ErrorResponseException | RegionConflictException | InsufficientDataException | XmlParserException
                | InternalException | IOException e) {
            log.error("创建Minio Bucket失败：{}", e.getMessage());
        }
        return client;
    }
}
